from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from drf_yasg import openapi
from rest_framework.views import APIView
from drf_yasg.utils import swagger_auto_schema
from .models import ProjectHistory
from .serializers import ProjectHistorySerializer
from ..ProjectsManagement.models import Project
from ..utils.response_utils import api_response, ResponseCode


class ListProjectHistoryView(APIView):
    """
    项目历史列表接口
    """

    @swagger_auto_schema(
        operation_description="获取项目历史列表",
        manual_parameters=[
            openapi.Parameter(
                'project_id',
                openapi.IN_QUERY,
                description="项目ID",
                type=openapi.TYPE_STRING,
                required=True
            ),
        ],
        responses={
            200: ProjectHistorySerializer,
            500: openapi.Response(
                description="服务器错误",
            )
        },
        tags=["项目历史管理"]
    )
    def get(self, request):
        project_id = request.query_params.get('project_id')
        try:
            queryset = ProjectHistory.objects.filter(project=project_id).order_by('-created_at')
            serializer = ProjectHistorySerializer(queryset, many=True)
            return api_response(ResponseCode.SUCCESS, "获取成功", serializer.data)
        except Exception as e:
            return api_response(ResponseCode.INTERNAL_SERVER_ERROR, str(e))


class CreateProjectHistoryView(APIView):
    """
    创建项目历史节点接口
    """

    @swagger_auto_schema(
        operation_description="创建项目历史节点（自动维护最多5个记录）",
        request_body=ProjectHistorySerializer,
        responses={
            200: ProjectHistorySerializer,
            400: "参数错误",
            404: "项目不存在"
        },
        tags=["项目历史管理"]
    )
    def post(self, request):
        try:
            # 验证项目存在性
            project_id = request.data.get('project')
            Project.objects.get(id=project_id)

            # 检查历史记录数量
            histories = ProjectHistory.objects.filter(project=project_id).order_by('created_at')
            if histories.count() >= 50:
                # 删除最旧的记录
                oldest_history = histories.first()
                oldest_history.delete()

            # 创建新记录
            serializer = ProjectHistorySerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return api_response(ResponseCode.SUCCESS, "历史节点创建成功", serializer.data)
            return api_response(ResponseCode.BAD_REQUEST, f"参数错误：{serializer.errors}")

        except ObjectDoesNotExist:
            return api_response(ResponseCode.NOT_FOUND, "指定项目不存在")
        except Exception as e:
            return api_response(ResponseCode.INTERNAL_SERVER_ERROR, f"服务器错误: {str(e)}")


class CurrentHistoryView(APIView):
    """获取当前激活的历史版本"""

    @swagger_auto_schema(
        operation_description="获取当前激活的历史版本",
        manual_parameters=[
            openapi.Parameter(
                'project_id',
                openapi.IN_QUERY,
                description="项目ID",
                type=openapi.TYPE_STRING,
                required=True
            ),
        ],
        responses={
            200: ProjectHistorySerializer,
            500: openapi.Response(
                description="服务器错误",
            )
        },
        tags=["项目历史管理"]
    )
    def get(self, request, project_id):
        try:
            current = ProjectHistory.objects.get(
                project_id=project_id,
                is_current=True
            )
            return api_response(
                ResponseCode.SUCCESS,
                "获取成功",
                ProjectHistorySerializer(current).data
            )
        except ObjectDoesNotExist:
            return api_response(ResponseCode.NOT_FOUND, "无激活版本")
        except Exception as e:
            return api_response(ResponseCode.INTERNAL_SERVER_ERROR, f"服务器错误: {str(e)}")


class ChangeCurrentHistoryView(APIView):
    """
    切换当前历史节点接口
    """

    @swagger_auto_schema(
        operation_description="切换当前历史节点",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['operation'],
            properties={
                'operation': openapi.Schema(
                    type=openapi.TYPE_STRING,
                    enum=['advance', 'back'],
                    description="操作类型：advance-前进，back-后退"
                )
            }
        ),
        responses={
            200: ProjectHistorySerializer,
            400: "参数错误",
            404: "项目不存在"
        },
        tags=["项目历史管理"]
    )
    def post(self, request):
        try:
            project_id = request.data.get('project')
            operation = request.data.get('operation')

            # 参数验证
            if not operation or operation not in ['advance', 'back']:
                return api_response(ResponseCode.BAD_REQUEST, "参数错误")

            # 获取当前版本
            current = ProjectHistory.objects.get(
                project_id=project_id,
                is_current=True
            )

            # 构建查询条件
            time_filter = {
                'back': ('created_at__lt', '-created_at'),
                'advance': ('created_at__gt', 'created_at')
            }[operation]

            # 获取相邻记录
            adjacent = ProjectHistory.objects.filter(
                project_id=project_id,
            **{time_filter[0]: current.created_at}
            ).order_by(time_filter[1]).first()

            if not adjacent:
                return api_response(
                    ResponseCode.BAD_REQUEST,
                    "无法继续{}操作".format('后退' if operation == 'back' else '前进')
                )

            # 事务操作
            with transaction.atomic():
                current.is_current = False
                current.save(update_fields=['is_current'])

                adjacent.is_current = True
                adjacent.save(update_fields=['is_current'])

            return api_response(
                ResponseCode.SUCCESS,
                "操作成功",
                ProjectHistorySerializer(adjacent).data
            )

        except ObjectDoesNotExist:
            return api_response(ResponseCode.NOT_FOUND, "当前无激活版本")
        except Exception as e:
            return api_response(ResponseCode.INTERNAL_SERVER_ERROR, f"操作失败: {str(e)}")